//
//  VipInfoTableViewCell.swift
//  LeTu
//
//  Created by g1 on 2023/12/31.
//

import UIKit
import ActiveLabel

class VipInfoTableViewCell: BaseTableViewCell {

    private var sourceArr = [VipPirceModel]()
    private var currentIndex = 0
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        configUI()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        DispatchQueue.main.async {
            self.vipIconImgView.layerCornerRadius(self.vipIconImgView.height/2)
            self.avatarBackView.layerCornerRadius(self.avatarBackView.height/2)
            self.avatarImgView.layerCornerRadius(self.avatarImgView.height/2)
            self.userInfoBackView.addGradientLayer(gradientColors:  [UIColor.hex(hexString: "#FFF7EB"),UIColor.hex(hexString: "#EFFFFE")], gradientDirection: .horizontally)
            self.vipBackView.layerCornerRadius(18, [.topLeft, .topRight])
            self.openBtn.layerCornerRadius(self.openBtn.height/2)
        }
    }
    static func getCellHeight() -> CGFloat {
        
        let vipCardHeight = (14+(screenWidth-16*2)*197/380)
        let pricePromptHeight = 32+20.0
        let priceCollectionViewHeight = 10+148.0
        let openBtnHeight = 30+CGFloat.app_btnHeight
        
        
        
        let protocolLabelHeight = 14+16.0
        
        let isVip = kUserManager.userModel.memberName.count > 0
        let attri: ASAttributedString = "\(isVip ? "会员可无限畅听平台内所有音频内容".localized:"开通会员，可无限畅听平台内所有音频内容".localized, .kern(1))"
        let vipDefaultHeight = attri.value.height(constrainedToWidth: screenWidth-48)+2
        
        return 16 + 110 + 16 + (16.0+24.0) + vipDefaultHeight + vipCardHeight + pricePromptHeight + priceCollectionViewHeight + openBtnHeight + protocolLabelHeight + 20
    }
    func updateUserInfo() {
        
        let isVip = kUserManager.userModel.memberName.count > 0
        let memberName = kUserManager.userModel.memberName
        
        avatarImgView.sd_setImage(with: URL.encodedURL(string: kUserManager.userModel.avatar), placeholderImage: UIImage(named: "avatar_placeholder"))
                
        nicknameLabel.text = kUserManager.userModel.nickname.count > 0 ? kUserManager.userModel.nickname:Utils.hideMiddleDigitsInPhoneNumber(kUserManager.userModel.mobile)
        vipInfolabel.attributed.text = isVip ? "\(.image(UIImage(named: "vip_golden")!, .custom(.offset(CGPoint(x: 0, y: -2)), size: CGSize(width: 20, height: 12))))\(memberName.localized)":""
        
        vipPromptLabel.text = "开通会员 无限畅听".localized
        vipDetailLabel.attributed.text = "\("开通会员，可无限畅听平台内所有音频内容".localized, .kern(1))"
        vipCardContentLabel.text = "开通会员 无限畅听".localized
        vipCardDetailLabel.attributed.text = "\("开通会员，可无限畅听平台内所有音频内容".localized, .kern(2.2))"
        openBtn.setTitle(isVip ? "立即开通".localized:"立即开通 无限畅听".localized)
        
    }
    func setVipPrices(_ prices: [VipPirceModel]) {
        sourceArr = prices
        priceCollectionView.reloadData()
    }
    
    // MARK: - UIButtonAction
    @objc func openBtnAction() {
        let priceModel = sourceArr[currentIndex]
        send(event: VipCenterVC.TransferEvent.openVip(priceModel: priceModel))
    }
    
    // MARK: - configUI
    func configUI() {
        
        contentView.addSubview(backView)
        backView.addSubview(userInfoBackView)
        userInfoBackView.addSubview(avatarBackView)
        userInfoBackView.addSubview(avatarImgView)
        backView.addSubview(vipIconImgView)
        userInfoBackView.addSubview(userBackView)
        userBackView.addSubview(nicknameLabel)
        userBackView.addSubview(vipInfolabel)
        
        backView.addSubview(vipBackView)
        vipBackView.addSubview(vipPromptLabel)
        vipBackView.addSubview(vipDetailLabel)
        vipBackView.addSubview(vipCardBackImgView)
        vipCardBackImgView.addSubview(vipCardContentView)
        vipCardContentView.addSubview(vipCardTitleContentView)
        vipCardTitleContentView.addSubview(vipCardLogoImgView)
        vipCardTitleContentView.addSubview(vipCardContentLabel)
        vipCardContentView.addSubview(vipCardDetailLabel)
        vipBackView.addSubview(priceTypeLabel)
        vipBackView.addSubview(priceCollectionView)
        vipBackView.addSubview(openBtn)
        vipBackView.addSubview(protocolLabel)
        
        backView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(16)
        }
        userInfoBackView.snp.makeConstraints { make in
            make.height.equalTo(108)
            make.top.equalToSuperview()
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        avatarBackView.snp.makeConstraints { make in
            make.width.height.equalTo(60)
            make.left.equalTo(28)
            make.centerY.equalToSuperview()
        }
        avatarImgView.snp.makeConstraints { make in
            make.left.top.equalTo(avatarBackView).offset(2)
            make.bottom.right.equalTo(avatarBackView).offset(-2)
        }
        vipIconImgView.snp.makeConstraints { make in
            make.centerX.equalTo(avatarImgView.snp.right).offset(-10)
            make.bottom.equalTo(avatarBackView)
            make.width.height.equalTo(20)
        }
        userBackView.snp.makeConstraints { make in
            make.left.equalTo(avatarBackView.snp.right).offset(10)
            make.centerY.right.equalToSuperview()
        }
        nicknameLabel.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
        }
        vipInfolabel.snp.makeConstraints { make in
            make.top.equalTo(nicknameLabel.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
        vipBackView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(userInfoBackView.snp.bottom).offset(16)
        }
        vipPromptLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.top.equalTo(16)
            make.height.equalTo(24)
        }
        vipDetailLabel.snp.makeConstraints { make in
            make.left.right.equalTo(vipPromptLabel)
            make.top.equalTo(vipPromptLabel.snp.bottom)
        }
        vipCardBackImgView.snp.makeConstraints { make in
            make.left.equalTo(userInfoBackView)
            make.top.equalTo(vipDetailLabel.snp.bottom).offset(14)
            make.width.equalTo(screenWidth-16*2)
            make.height.equalTo(vipCardBackImgView.snp.width).multipliedBy(197.0/380.0)
        }
        vipCardContentView.snp.makeConstraints { make in
            make.centerY.left.right.equalToSuperview()
        }
        vipCardTitleContentView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.left.greaterThanOrEqualToSuperview().offset(16)
            make.right.lessThanOrEqualToSuperview().offset(-16)
            make.width.lessThanOrEqualToSuperview().offset(-32)
        }
        vipCardLogoImgView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(5)
            make.width.equalTo(40)
            make.height.equalTo(24)
        }
        vipCardContentLabel.snp.makeConstraints { make in
            make.left.equalTo(vipCardLogoImgView.snp.right).offset(4)
            make.top.right.bottom.equalToSuperview()
            make.height.greaterThanOrEqualTo(24)
        }
        vipCardDetailLabel.snp.makeConstraints { make in
            make.top.equalTo(vipCardTitleContentView.snp.bottom).offset(12)
            make.bottom.equalToSuperview()
            make.left.right.equalTo(vipCardTitleContentView)
        }
        priceTypeLabel.snp.makeConstraints { make in
            make.left.right.equalTo(vipPromptLabel)
            make.top.equalTo(vipCardBackImgView.snp.bottom).offset(32)
            make.height.equalTo(20)
        }
        priceCollectionView.snp.makeConstraints { make in
            make.left.right.equalTo(vipCardBackImgView)
            make.top.equalTo(priceTypeLabel.snp.bottom).offset(10)
            make.height.equalTo(148)
        }
        openBtn.snp.makeConstraints { make in
            make.left.right.equalTo(priceTypeLabel)
            make.height.equalTo(CGFloat.app_btnHeight)
            make.top.equalTo(priceCollectionView.snp.bottom).offset(30)
        }
        protocolLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(openBtn.snp.bottom).offset(14)
        }
        
        configAgreementPromptLabel()
        
        priceCollectionView.delegate = self
        priceCollectionView.dataSource = self
        priceCollectionView.register(cellClass: VipPirceItemColelctionViewCell.self)
        
        openBtn.addTarget(self, action: #selector(openBtnAction))
        
    }
    func configAgreementPromptLabel() {
        
        let customType1Name = "《用户会员服务协议》"

        let customType1 = ActiveType.custom(pattern: customType1Name)
        
        protocolLabel.enabledTypes = [customType1]
        protocolLabel.font = kSetPingFangRegular(12)
        protocolLabel.customColor[customType1] = .app_themeColor

        protocolLabel.text = "开通即表示同意\(customType1Name)".localized
        protocolLabel.handleCustomTap(for: customType1, handler: { (customType) in
            guard let currentVC = Utils.getTopVC() else { return }
            currentVC.present(BaseNavigationController(rootViewController: AppWebViewController(url: kUserProtocalUrl, isShowNav: true)), animated: true, completion: nil)
        })
        
    }
    private lazy var backView: UIView = {
        let backView = UIView()
        return backView
    }()
    // - 用户信息
    private lazy var userInfoBackView: UIView = {
        let userInfoBackView = UIView()
        userInfoBackView.layer.cornerRadius = 16
        userInfoBackView.layer.masksToBounds = true
        return userInfoBackView
    }()
    private lazy var avatarBackView: UIView = {
        let avatarBackView = UIView()
        avatarBackView.backgroundColor = UIColor(red: 0.879, green: 0.781, blue: 0.59, alpha: 1)
        return avatarBackView
    }()
    private lazy var avatarImgView: UIImageView = {
        let avatarImgView = UIImageView()
        avatarImgView.contentMode = .scaleAspectFill
        avatarImgView.image = UIImage(named: "avatar_placeholder")
        return avatarImgView
    }()
    private lazy var vipIconImgView: UIButton = {
        let vipIconImgView = UIButton()
        vipIconImgView.isEnabled = false
        vipIconImgView.backgroundColor = UIColor(red: 0.945, green: 0.992, blue: 0.988, alpha: 1)
        vipIconImgView.setImage(UIImage(named: "vip_white"), for: .disabled)
        vipIconImgView.imageEdgeInsets = UIEdgeInsets(top: 6, left: 5, bottom: 6, right: 3)
        return vipIconImgView
    }()
    private lazy var userBackView = UIView()
    private lazy var nicknameLabel: UILabel = {
        let nicknameLabel = UILabel()
        nicknameLabel.font = kSetPingFangMedium(18)
        return nicknameLabel
    }()
    private lazy var vipInfolabel: UILabel = {
        let vipInfolabel = UILabel()
        vipInfolabel.font = kSetPingFangRegular(12)
        vipInfolabel.textColor = .app_lightGolden
        return vipInfolabel
    }()
    // - vip信息
    private lazy var vipBackView: UIView = {
        let vipBackView = UIView()
        vipBackView.backgroundColor = .app_white
        return vipBackView
    }()
    private lazy var vipPromptLabel: UILabel = {
        let vipPromptLabel = UILabel()
        vipPromptLabel.font = kSetPingFangMedium(16)
        vipPromptLabel.numberOfLines = 0
        return vipPromptLabel
    }()
    private lazy var vipDetailLabel: UILabel = {
        let vipDetailLabel = UILabel()
        vipDetailLabel.font = kSetPingFangRegular(12)
        vipDetailLabel.textColor = .app_detaisltextColor
        vipDetailLabel.numberOfLines = 0
        return vipDetailLabel
    }()
    // - vip卡片信息
    private lazy var vipCardBackImgView: UIImageView = {
        let vipCardBackImgView = UIImageView()
        vipCardBackImgView.image = UIImage(named: "vip_card_big_background")
        return vipCardBackImgView
    }()
    private var vipCardContentView = UIView()
    private var vipCardTitleContentView = UIView()
    private lazy var vipCardLogoImgView: UIImageView = {
        let vipCardLogoImgView = UIImageView()
        vipCardLogoImgView.image = UIImage(named: "card_vip_golden")
        return vipCardLogoImgView
    }()
    private lazy var vipCardContentLabel: UILabel = {
        let vipCardContentLabel = UILabel()
        vipCardContentLabel.font = kSetPingFangMedium(24)
        vipCardContentLabel.textColor = .app_golden
        vipCardContentLabel.numberOfLines = 0
        return vipCardContentLabel
    }()
    private lazy var vipCardDetailLabel: UILabel = {
        let vipCardDetailLabel = UILabel()
        vipCardDetailLabel.font = kSetPingFangRegular(12)
        vipCardDetailLabel.textColor = .app_detaisltextColor
        vipCardDetailLabel.textColor = .app_golden
        vipCardDetailLabel.numberOfLines = 0
        return vipCardDetailLabel
    }()
    // - 价格列表
    private lazy var priceTypeLabel: UILabel = {
        let priceTypeLabel = UILabel()
        priceTypeLabel.text = "请选择开通类型".localized // 如累积开通请选择开通类型
        priceTypeLabel.font = kSetPingFangMedium(14)
        return priceTypeLabel
    }()
    private lazy var priceCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        let priceCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        priceCollectionView.backgroundColor = .clear
        priceCollectionView.showsHorizontalScrollIndicator = false
        return priceCollectionView
    }()
    private lazy var openBtn: CustomClickableView = {
        let openBtn = CustomClickableView()
        openBtn.setFont(kSetPingFangBlod(16))
        openBtn.backgroundColor = .app_themeColor
        return openBtn
    }()
    private lazy var protocolLabel: ActiveLabel = {
        let protocolLabel = ActiveLabel()
        protocolLabel.font = kSetPingFangRegular(11)
        protocolLabel.textColor = UIColor(red: 0.494, green: 0.51, blue: 0.514, alpha: 1)
        protocolLabel.numberOfLines = 0
        return protocolLabel
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

extension VipInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.height, height: collectionView.height)
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sourceArr.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(VipPirceItemColelctionViewCell.self, indexPath: indexPath)
        cell.setInfo(priceModel: sourceArr[indexPath.item], isSelect: currentIndex == indexPath.row)
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        currentIndex = indexPath.item
        collectionView.reloadData()
    }
    
}

class VipPirceItemColelctionViewCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configUI()
    }
    
    func setInfo(priceModel: VipPirceModel, isSelect: Bool) {
            
        titleLabel.text = LanguageManager.shared.currentLanguage == .zh ? priceModel.name:priceModel.englishName
        
        priceLabel.attributed.text = "\("¥", .font(kSetPingFangBlod(20)))\(priceModel.productPrice)"
        
        backView.layer.borderColor = isSelect ? UIColor.hex(hexString: "#F1DDA8").cgColor:UIColor.hex(hexString: "#F3F3F3").cgColor
        backView.backgroundColor = isSelect ? UIColor.hex(hexString: "#FBF8EC"):UIColor.hex(hexString: "#F3F3F3")
    }
    
    // MARK: - configUI
    func configUI() {
        
        contentView.addSubview(backView)
        backView.addSubview(contentBackView)
        contentBackView.addSubview(priceLabel)
        contentBackView.addSubview(titleLabel)
        
        backView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        contentBackView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.centerY.equalToSuperview().offset(-2)
        }
        priceLabel.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(48)
        }
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(priceLabel.snp.bottom).offset(8)
            make.bottom.equalToSuperview()
            make.left.equalTo(6)
            make.right.equalTo(-6)
        }
        
    }
    private lazy var backView: UIView = {
        let backView = UIView()
        backView.layer.cornerRadius = 16
        backView.layer.masksToBounds = true
        backView.layer.borderWidth = 3
        backView.layer.borderColor = UIColor.hex(hexString: "#F3F3F3").cgColor
        return backView
    }()
    private lazy var contentBackView = UIView()
    private lazy var priceLabel: UILabel = {
        let priceLabel = UILabel()
        priceLabel.font = kSetPingFangBlod(40)
        priceLabel.textColor = .app_priceTextColor
        priceLabel.textAlignment = .center
        return priceLabel
    }()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.font = kSetPingFangMedium(17)
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        return titleLabel
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


